package com.zygk.library.util;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Environment;
import com.nanchen.compresshelper.CompressHelper;
import com.yanzhenjie.nohttp.RequestMethod;
import com.yanzhenjie.nohttp.rest.Response;
import com.yanzhenjie.nohttp.rest.SimpleResponseListener;
import com.yanzhenjie.nohttp.rest.StringRequest;
import com.zygk.library.config.LibraryConstants;
import com.zygk.library.model.CommonResult;
import java.io.File;
import java.util.LinkedHashMap;
import java.util.UUID;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by Wikison on 2017/12/5.
 * 网络请求
 */
public abstract class HttpRequest {

  public interface HttpListener<T> {
    void onStart(int what);

    void onSucceed(int what, Response<T> response);

    void onFailed(int what, Response<T> response);

    void onFinish(int what);
  }

  public interface HttpCallback {
    void onStart();

    void onSucceed(Object obj);

    void onFailed();

    void onFinish();
  }

  /**
   * 车牌识别
   */
  public static void ocr_vehicle_plate(final Context mContext, String path,
      final HttpCallback callback) {

    File oldFile = new File(path);
    if (oldFile == null) return;

    try {
      File newFile = new CompressHelper.Builder(mContext).setMaxWidth(420)  // 默认最大宽度为720
          .setMaxHeight(420) // 默认最大高度为960
          .setQuality(80)    // 默认压缩质量为80
          .setCompressFormat(Bitmap.CompressFormat.PNG) // 设置默认压缩为jpg格式
          .setDestinationDirectoryPath(
              Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
                  .getAbsolutePath()).build().compressToFile(oldFile);

      String base64 = ImageUtil.getBase64(newFile);
      StringRequest request =
          new StringRequest(LibraryConstants.OCR_VEHICLE_URL, RequestMethod.POST);
      request.addHeader("Authorization", "APPCODE " + "afe19ce318214df6a46a7c750ea1ff15");
      request.addHeader("Content-Type", "application/json; charset=UTF-8");

      String bodys = "{\"inputs\": [{\"image\": {\"dataType\": 50,\"dataValue\": \""
          + base64
          + "\"},\"configure\": {\"dataType\": 50,\"dataValue\": \"{\\\"multi_crop\\\": false}\"}}]}";
      request.setDefineRequestBodyForJson(bodys); // 传入json格式的字符串即可。

      SimpleResponseListener<String> listener = new SimpleResponseListener<String>() {
        @Override public void onStart(int what) {
          super.onStart(what);
          callback.onStart();
        }

        @Override public void onSucceed(int what, Response<String> response) {
          super.onSucceed(what, response);

          try {
            JSONObject jsonObject = new JSONObject(response.get());
            JSONArray outputs = jsonObject.getJSONArray("outputs");
            JSONObject outputValue = outputs.getJSONObject(0).getJSONObject("outputValue");
            String dataValue = outputValue.getString("dataValue");

            JSONObject dv = new JSONObject(dataValue);
            boolean success = dv.getBoolean("success");

            if (success) {
              JSONObject plate = dv.getJSONArray("plates").getJSONObject(0);
              String plateNum = plate.getString("txt");

              callback.onSucceed(plateNum);
            } else {
              callback.onFailed();
            }
          } catch (JSONException e) {
            callback.onFailed();
          }
        }

        @Override public void onFailed(int what, Response<String> response) {
          super.onFailed(what, response);
          callback.onFailed();
        }

        @Override public void onFinish(int what) {
          super.onFinish(what);
          callback.onFinish();
        }
      };
      CallServer.getInstance().request(0, request, listener);
    } catch (Exception e) {
      ToastUtil.showMessage(mContext, "该图片格式错误，请重新选择！");
    }
  }

  public static void net(StringRequest request, final HttpListener httpListener) {
    String appID = "android-manual";
    String nonce_str = UUID.randomUUID().toString().toLowerCase();
    String timestamp = DateTimeUtil.getCurrentTime();
    String sign = Security.encryptByMD5(
        "appID=" + appID + "&nonce_str=" + nonce_str + "&timestamp=" + timestamp);

    LinkedHashMap<String, Object> map = new LinkedHashMap<>();
    map.put("appID", appID);
    map.put("nonce_str", nonce_str);
    map.put("timestamp", timestamp);
    map.put("sign", sign);

    String encodeString= Base64.encode(JsonUtil.objectToJson(map).getBytes());
    request.add("signHead", encodeString);

    SimpleResponseListener<String> listener = new SimpleResponseListener<String>() {
      @Override public void onStart(int what) {
        super.onStart(what);
        httpListener.onStart(what);
      }

      @Override public void onSucceed(int what, Response<String> response) {
        super.onSucceed(what, response);
        CommonResult result = JsonUtil.jsonToObject(response.get().toString(), CommonResult.class);
        if (result == null) {
          return;
        }
        httpListener.onSucceed(what, response);
      }

      @Override public void onFailed(int what, Response<String> response) {
        super.onFailed(what, response);
        httpListener.onFailed(what, response);
      }

      @Override public void onFinish(int what) {
        super.onFinish(what);
        httpListener.onFinish(what);
      }
    };
    CallServer.getInstance().request(0, request, listener);
  }
}